﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Infrastructure;
using System.Collections.ObjectModel;
using System.Threading;
using DBDataAccessLib.DataMapping;
using System.IO;
using Microsoft.Practices.Prism.Commands;
using DBDataAccessLib;
using System.ComponentModel;
using System.Collections;
using System.Globalization;
using ManageInfo.View;
using Infrastructure.Events;
using Microsoft.Practices.ServiceLocation;
using Microsoft.Practices.Prism.Events;
using System.Windows;
using System.Data;
using Telerik.Windows.Controls;
using UserControlLib;
using PluginManager;

namespace ManageInfo.ViewModel
{
    public class ManageInfoViewModel : Infrastructure.ViewModelBase
    {
        private EditMachineInfo editWindow = null;
        private PlayInfoWindow window;
        public ManageInfoViewModel()
        {
            SaveCommand = new DelegateCommand<object>(OnSaveCommand, OnCanSaveCommand);
            PreviewCommand = new DelegateCommand<object>(OnPreviewCommand, OnCanPreviewCommand);
            ApplyCommand = new DelegateCommand<object>(OnApplyCommand, OnCanApplyCommand);
            EditCommand = new DelegateCommand<object>(OnEditCommand, OnCanEditCommand);
            DeleteCommand = new DelegateCommand<object>(OnDeleteCommand, OnCanDeleteCommand);
            ExportCommand = new DelegateCommand<object>(OnExportCommand, OnCanExportCommand);
            window = new PlayInfoWindow();
            ServiceLocator.Current.GetInstance<IEventAggregator>().GetEvent<EditAccomplished>().Subscribe(OnEditAccomplished);
            SetValues();
        }

        public override void OnRemoved()
        {
            window.CloseWindow();
        }

        public void OnEditAccomplished(object payload)
        {
            editWindow.Close();
            SaveCommand.Execute(null);
        }

        public DependencyObject View { get; set; }

        public void OnEditCommand(object obj)
        {
            editWindow = new EditMachineInfo();
            editWindow.Owner = View.ParentOfType<Window>();
            editWindow.mic.MachineInfo = SelectedMachineInfo;
            editWindow.ShowDialog();
        }

        public void OnPreviewCommand(object obj)
        {
            if (string.IsNullOrWhiteSpace(SelectedMachineInfo.Essentials))
            {
                ModalWindowService.ShowMessage("没有可以显示的图片。");
                return;
            }
            string[] paths = SelectedMachineInfo.Essentials.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
            if (!Directory.Exists(Helper.ServerUrl + SelectedMachineInfo.WCNO + "\\" + SelectedMachineInfo.StationName))
            {
                ModalWindowService.ShowMessage("没有需要显示的图片。");
                return;
            }
            string[] files = Directory.GetFiles(Helper.ServerUrl + SelectedMachineInfo.WCNO + "\\" + SelectedMachineInfo.StationName);
            foreach (var pa in paths)
            {
                bool fileExist = false;
                foreach (var f in files)
                {
                    FileInfo info = new FileInfo(f);
                    if (info.Name == pa)
                    {
                        fileExist = true;
                        break;
                    }
                }
                if (!fileExist)
                {
                    ModalWindowService.ShowMessage("需要播放的文件：" + pa + "不存在。");
                    return;
                }
            }
            window.Record = SelectedMachineInfo;
            window.Reset();
            window.Show();
            window.Activate();
        }

        public bool OnCanPreviewCommand(object obj)
        {
            return SelectedMachineInfo != null;
        }

        public void OnDeleteCommand(object obj)
        {
            ModalWindowService.ShowConfirmMessage("确定要删除选中的记录吗？", result =>
            {
                if (MessageBoxResult.Yes == result)
                {
                    this.IsBusy = true;
                    MessageContent = "正在删除...";
                    ThreadPool.QueueUserWorkItem(new WaitCallback(currentContext =>
                    {
                        SynchronizationContext context = currentContext as SynchronizationContext;
                        bool isSuccess = true;
                        int val = MachineInfoDataAccess.DeleteMachineInfo(
                            this.SelectedMachineInfo.WCNO,
                            this.SelectedMachineInfo.StationName,
                            this.SelectedMachineInfo.Model);
                        context.Send(new SendOrPostCallback(p =>
                        {
                            IsBusy = false;
                            if (isSuccess)
                            {
                                ModalWindowService.ShowMessage("删除成功。");
                                SaveCommand.Execute(null);
                            }
                            else ModalWindowService.ShowMessage("删除失败。");
                        }), null);
                    }), SynchronizationContext.Current);
                }
            });
        }

        public bool OnCanDeleteCommand(object obj)
        {
            return SelectedMachineInfo != null && SelectedMachineInfo.Valid == 0;
        }

        public void OnExportCommand(object obj)
        {
            ModalWindowService.ShowConfirmMessage("确定要导出吗？", result =>
            {
                if (MessageBoxResult.Yes == result)
                {
                    this.IsBusy = true;
                    MessageContent = "正在导出...";
                    ThreadPool.QueueUserWorkItem(new WaitCallback(currentContext =>
                    {
                        SynchronizationContext context = currentContext as SynchronizationContext;
                        bool isSuccess = true;
                        string errorMsg = string.Empty;
                        try
                        {
                            Helper.ExportCSV(MachineInfo.ToDataTable(), Helper.BaseUri + "机种生产指示信息.csv");
                        }
                        catch (Exception ex)
                        {
                            isSuccess = false;
                            errorMsg = ex.Message;
                            throw;
                        }
                        context.Send(new SendOrPostCallback(p =>
                        {
                            IsBusy = false;
                            if (isSuccess) ModalWindowService.ShowMessage("导出成功。文件路径为：" + Helper.BaseUri + "机种生产指示信息.csv");
                            else ModalWindowService.ShowMessage("导出失败。" + errorMsg);
                        }), null);
                    }), SynchronizationContext.Current);
                }
            });
        }

        public bool OnCanExportCommand(object obj)
        {
            if (MachineInfo == null) return false;
            return MachineInfo.Count > 0;
        }

        public bool OnCanEditCommand(object obj)
        {
            return SelectedMachineInfo != null && SelectedMachineInfo.Valid == 0;
        }

        public bool OnCanApplyCommand(object obj)
        {
            return SelectedMachineInfo != null && SelectedMachineInfo.Valid == 0;
        }

        public void OnApplyCommand(object obj)
        {
            this.IsBusy = true;
            MessageContent = "正在应用...";
            ThreadPool.QueueUserWorkItem(new WaitCallback(currentContext =>
            {
                SynchronizationContext context = currentContext as SynchronizationContext;
                string message = MachineInfoDataAccess.ApplyMachineInfoByPrimKey(SelectedMachineInfo.WCNO, SelectedMachineInfo.StationName, SelectedMachineInfo.Model, (GeneralInformation.ViewStates["UserInfo"] as AccountMapping).UserName, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                context.Send(new SendOrPostCallback(p =>
                       {
                           IsBusy = false;
                           if (string.IsNullOrWhiteSpace(message))
                           {
                               ModalWindowService.ShowMessage("应用成功。");
                               SaveCommand.Execute(null);
                           }
                           else ModalWindowService.ShowMessage("应用失败：" + message);
                       }), null);
            }), SynchronizationContext.Current);
        }

        public void OnSaveCommand(object obj)
        {
            this.IsBusy = true;
            MessageContent = "正在查询...";
            ThreadPool.QueueUserWorkItem(new WaitCallback(currentContext =>
            {
                SynchronizationContext context = currentContext as SynchronizationContext;
                int currentValid = GetSelectedValid();
                List<MachineInfoRecordMapping> info = MachineInfoDataAccess.GetMachineInfoByConditions(wcno, selectedStationName, model, sebango,
                    selectedUserName);
                List<MachineInfoRecordMapping> filteredInfo = new List<MachineInfoRecordMapping>();
                foreach (var item in info)
                {
                    bool needInclude = true;
                    if (currentValid < 2)
                    {
                        if (item.Valid != currentValid) needInclude = false;
                    }
                    else
                    {
                        if (item.Valid < 2) needInclude = false;
                    }
                    if (needInclude)
                    {
                        foreach (var imageModel in ImageList)
                        {
                            if (imageModel.IsChecked && !item.Essentials.Contains(imageModel.ImagePath))
                            {
                                needInclude = false;
                                break;
                            }
                        }
                    }
                    if (needInclude)
                    {
                        if (FromDate.HasValue)
                        {
                            if (DateTime.ParseExact(item.SetDate, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture) >= FromDate.Value + TimeSpan.FromSeconds(0))
                                needInclude = true;
                            else needInclude = false;
                        }
                        if (ToDate.HasValue)
                        {
                            if (DateTime.ParseExact(item.SetDate, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture) <= ToDate.Value + TimeSpan.FromSeconds(59))
                                needInclude = true;
                            else needInclude = false;
                        }
                    }
                    if (needInclude) filteredInfo.Add(item);
                }
                context.Send(new SendOrPostCallback(p =>
                {
                    IsBusy = false;
                    MachineInfo = (p as List<MachineInfoRecordMapping>).ToObservableCollection();
                }), filteredInfo);
            }), SynchronizationContext.Current);
        }

        private int GetSelectedValid()
        {
            if (IsValidZeroChecked) return 0;
            else if (IsValidOneChecked) return 1;
            else return 2;
        }

        public bool OnCanSaveCommand(object obj)
        {
            if (fromDate.HasValue && toDate.HasValue)
            {
                if (toDate.Value >= fromDate.Value) return true;
                else return false;
            }
            return true;

        }

        public DelegateCommand<object> SaveCommand { get; set; }
        public DelegateCommand<object> ApplyCommand { get; set; }
        public DelegateCommand<object> PreviewCommand { get; set; }
        public DelegateCommand<object> EditCommand { get; set; }
        public DelegateCommand<object> ExportCommand { get; set; }
        public DelegateCommand<object> DeleteCommand { get; set; }

        private void SetValues()
        {
            this.IsBusy = true;
            MessageContent = "正在获取流水线信息...";
            ThreadPool.QueueUserWorkItem(new WaitCallback(currentContext =>
            {
                SynchronizationContext context = currentContext as SynchronizationContext;
                ObservableCollection<string> wcnos = StationNameDataAccess.GetAllWCNOLines().ToObservableCollection();
                wcnos.Insert(0, "");
                ObservableCollection<AccountMapping> names = UserDataAccess.GetAllAccounts().ToObservableCollection();
                names.Insert(0, new AccountMapping { UserName = "" });
                context.Send(new SendOrPostCallback(p =>
                {
                    IsBusy = false;
                    this.WCNOLines = (p as object[])[0] as ObservableCollection<string>;
                    this.UserNames = (p as object[])[1] as ObservableCollection<AccountMapping>;
                    if (WCNOLines.Count > 0) this.WCNO = this.WCNOLines.First();
                    if (UserNames.Count > 0) this.SelectedUserName = this.UserNames.First();
                }), new object[] { wcnos, names });
            }), SynchronizationContext.Current);
        }

        private ObservableCollection<MachineInfoRecordMapping> machineInfo;

        public ObservableCollection<MachineInfoRecordMapping> MachineInfo
        {
            get { return machineInfo; }
            set
            {
                machineInfo = value;
                OnPropertyChanged("MachineInfo");
                ExportCommand.RaiseCanExecuteChanged();
            }
        }


        private ObservableCollection<AccountMapping> userNames;

        public ObservableCollection<AccountMapping> UserNames
        {
            get { return userNames; }
            set
            {
                userNames = value;
                OnPropertyChanged("UserNames");
            }
        }

        private AccountMapping selectedUserName;

        public AccountMapping SelectedUserName
        {
            get { return selectedUserName; }
            set
            {
                if (value != null)
                {
                    selectedUserName = value;
                    OnPropertyChanged("SelectedUserName");
                }
            }
        }

        private MachineInfoRecordMapping selectedMachineInfo;

        public MachineInfoRecordMapping SelectedMachineInfo
        {
            get { return selectedMachineInfo; }
            set
            {
                selectedMachineInfo = value;
                OnPropertyChanged("SelectedMachineInfo");
                EditCommand.RaiseCanExecuteChanged();
                DeleteCommand.RaiseCanExecuteChanged();
                ApplyCommand.RaiseCanExecuteChanged();
                PreviewCommand.RaiseCanExecuteChanged();
            }
        }

        private string wcno;

        public string WCNO
        {
            get { return wcno; }
            set
            {
                if (wcno != value)
                {
                    wcno = value.Trim();
                    OnPropertyChanged("WCNO");
                    FillStationNames(value);
                    SaveCommand.RaiseCanExecuteChanged();
                }
            }
        }

        private void FillStationNames(string wcno)
        {
            this.IsBusy = true;
            MessageContent = "正在获取工位信息...";
            ThreadPool.QueueUserWorkItem(new WaitCallback(currentContext =>
            {
                SynchronizationContext context = currentContext as SynchronizationContext;
                ObservableCollection<string> stations = StationNameDataAccess.GetAllStationNames(wcno).ToObservableCollection();
                context.Send(new SendOrPostCallback(p =>
                {
                    IsBusy = false;
                    this.StationNames = p as ObservableCollection<string>;
                    this.StationNames.Insert(0, "");
                    if (StationNames.Count > 0) this.SelectedStationName = StationNames.First();
                }), stations);
            }), SynchronizationContext.Current);
        }

        private ObservableCollection<string> wcnoLines;

        public ObservableCollection<string> WCNOLines
        {
            get { return wcnoLines; }
            set
            {
                wcnoLines = value;
                OnPropertyChanged("WCNOLines");
            }
        }

        private ObservableCollection<string> stationNames;

        public ObservableCollection<string> StationNames
        {
            get { return stationNames; }
            set
            {
                stationNames = value;
                OnPropertyChanged("StationNames");
            }
        }

        private string selectedStationName;

        public string SelectedStationName
        {
            get { return selectedStationName; }
            set
            {
                if (selectedStationName != value)
                {
                    selectedStationName = value;
                    OnPropertyChanged("SelectedStationName");
                    FillImageList(value);
                    SaveCommand.RaiseCanExecuteChanged();
                }
            }
        }

        private DateTime? fromDate;

        public DateTime? FromDate
        {
            get { return fromDate; }
            set
            {
                if (fromDate != value)
                {
                    RemoveError("FromDate");
                    RemoveError("ToDate");

                    fromDate = value;

                    if (fromDate.HasValue && toDate.HasValue && fromDate.Value > toDate.Value)
                    {
                        AddError("FromDate", "开始时间大于结束时间");
                        AddError("ToDate", "结束时间小于开始时间");
                    }
                    OnPropertyChanged("FromDate");
                    OnPropertyChanged("ToDate");
                    SaveCommand.RaiseCanExecuteChanged();
                }
            }
        }

        private DateTime? toDate;

        public DateTime? ToDate
        {
            get { return toDate; }
            set
            {
                if (toDate != value)
                {
                    RemoveError("FromDate");
                    RemoveError("ToDate");

                    toDate = value;

                    if (fromDate.HasValue && toDate.HasValue && fromDate.Value > toDate.Value)
                    {
                        AddError("FromDate", "开始时间大于结束时间");
                        AddError("ToDate", "结束时间小于开始时间");
                    }
                    OnPropertyChanged("FromDate");
                    OnPropertyChanged("ToDate");
                    SaveCommand.RaiseCanExecuteChanged();
                }
            }
        }

        private void FillImageList(string stationName)
        {
            this.IsBusy = true;
            MessageContent = "正在获取图片信息...";
            ThreadPool.QueueUserWorkItem(new WaitCallback(currentContext =>
            {
                SynchronizationContext context = currentContext as SynchronizationContext;
                ObservableCollection<ImageListModel> models = new ObservableCollection<ImageListModel>();
                if (Directory.Exists(Helper.ServerUrl + WCNO + "\\" + stationName))
                {
                    foreach (var path in Directory.GetFiles(Helper.ServerUrl + WCNO + "\\" + stationName))
                    {
                        FileInfo info = new FileInfo(path);
                        if (info.Extension.ToLower() == ".jpg" || info.Extension.ToLower() == ".jpeg")
                        {
                            models.Add(new ImageListModel { ImagePath = info.Name, FullPath = path, IsChecked = false });
                        }
                    }
                }
                context.Send(new SendOrPostCallback(p =>
                {
                    IsBusy = false;
                    this.ImageList = p as ObservableCollection<ImageListModel>;
                }), models);
            }), SynchronizationContext.Current);
        }

        private string model;

        public string Model
        {
            get { return model; }
            set
            {
                model = value.Trim();
                OnPropertyChanged("Model");
                SaveCommand.RaiseCanExecuteChanged();
            }
        }

        private string sebango;

        public string Sebango
        {
            get { return sebango; }
            set
            {
                sebango = value.Trim();
                OnPropertyChanged("Sebango");
                SaveCommand.RaiseCanExecuteChanged();
            }
        }

        private bool isValidZeroChecked = true;

        public bool IsValidZeroChecked
        {
            get { return isValidZeroChecked; }
            set
            {
                isValidZeroChecked = value;
                OnPropertyChanged("IsValidZeroChecked");
            }
        }

        private bool isValidOneChecked;

        public bool IsValidOneChecked
        {
            get { return isValidOneChecked; }
            set
            {
                isValidOneChecked = value;
                OnPropertyChanged("IsValidOneChecked");
            }
        }
        private bool isValidTwoChecked;

        public bool IsValidTwoChecked
        {
            get { return isValidTwoChecked; }
            set
            {
                isValidTwoChecked = value;
                OnPropertyChanged("IsValidTwoChecked");
            }
        }
        private ObservableCollection<ImageListModel> imageList;

        public ObservableCollection<ImageListModel> ImageList
        {
            get { return imageList; }
            set
            {
                imageList = value;
                OnPropertyChanged("ImageList");
            }
        }

        private ImageListModel selectedImageModel;

        public ImageListModel SelectedImageModel
        {
            get { return selectedImageModel; }
            set
            {
                selectedImageModel = value;
                OnPropertyChanged("SelectedImageModel");
            }
        }
    }

    public class ImageListModel : Infrastructure.ViewModelBase
    {
        private bool isChecked;

        public bool IsChecked
        {
            get { return isChecked; }
            set
            {
                isChecked = value;
                OnPropertyChanged("IsChecked");
            }
        }

        private string imagePath;

        public string ImagePath
        {
            get { return imagePath; }
            set { imagePath = value; }
        }

        private string fullPath;

        public string FullPath
        {
            get { return fullPath; }
            set { fullPath = value; }
        }


    }
}
